package com.ruoyi.web.controller.gcgl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gcgl.domain.GcProject;
import com.ruoyi.gcgl.domain.GcProjectFlow;
import com.ruoyi.gcgl.domain.GcProjectQtwj;
import com.ruoyi.gcgl.service.IGcProjectFlowService;
import com.ruoyi.gcgl.service.IGcProjectQtwjService;
import com.ruoyi.gcgl.service.IGcProjectService;

/**
 * 其他文件Controller
 * 
 * @author ruoyi
 * @date 2022-11-27
 */
@Controller
@RequestMapping("/gcgl/qtwj")
public class GcProjectQtwjController extends BaseController{
	
	private static final Logger log = LoggerFactory.getLogger(GcProjectQtwjController.class);
	
    private String prefix = "gcgl/qtwj";

    @Autowired
    private IGcProjectQtwjService gcProjectQtwjService;
    @Autowired
    private IGcProjectService gcProjectService;
    @Autowired
    private IGcProjectFlowService gcProjectFlowService;
    @Autowired
    private ServerConfig serverConfig;
    
    private static final String FILE_DELIMETER = ",";

    @RequiresPermissions("gcgl:qtwj:view")
    @GetMapping()
    public String qtwj()
    {
        return prefix + "/qtwj";
    }

    /**
     * 查询其他文件列表
     */
    @RequiresPermissions("gcgl:qtwj:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GcProjectQtwj gcProjectQtwj)
    {
        startPage();
        gcProjectQtwj.setDeleteFlag(1);
        if(getSysUser().isShow43R(getUserId())){
        gcProjectQtwj.setCreateUser(getLoginName());
        }
        List<GcProjectQtwj> list = gcProjectQtwjService.selectGcProjectQtwjList(gcProjectQtwj);
        
        for(GcProjectQtwj obj:list){
        	GcProject project = gcProjectService.selectGcProjectById(obj.getGcProjectid());
        	obj.setStatus(project.getStatus());
        }
        return getDataTable(list);
    }

    /**
     * 导出其他文件列表
     */
    @RequiresPermissions("gcgl:qtwj:export")
    @Log(title = "其他文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GcProjectQtwj gcProjectQtwj)
    {
    	gcProjectQtwj.setDeleteFlag(1);
    	if(getSysUser().isShow()){
            gcProjectQtwj.setCreateUser(getLoginName());
            }
        List<GcProjectQtwj> list = gcProjectQtwjService.selectGcProjectQtwjList(gcProjectQtwj);
        ExcelUtil<GcProjectQtwj> util = new ExcelUtil<GcProjectQtwj>(GcProjectQtwj.class);
        return util.exportExcel(list, "其他文件数据");
    }

    /**
     * 新增其他文件
     */
    @GetMapping("/add/{gcProjectid}")
    public String add(ModelMap mmap,@PathVariable("gcProjectid") Long gcProjectid){
    	GcProject gcProject = gcProjectService.selectGcProjectById(gcProjectid);
    	mmap.put("gcProject", gcProject);
        return prefix + "/add";
    }

    /**
     * 新增保存其他文件
     */
    @RequiresPermissions("gcgl:qtwj:add")
    @Log(title = "其他文件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public synchronized AjaxResult addSave(GcProjectQtwj gcProjectQtwj){
    	
    	try{
            gcProjectQtwj.setDeleteFlag(1);
            gcProjectQtwj.setCreateAt(new Date());
            gcProjectQtwj.setUpdateAt(new Date());
            gcProjectQtwj.setCreateUser(getLoginName());
            gcProjectQtwj.setUpdateUser(getLoginName());
        	gcProjectQtwjService.insertGcProjectQtwj(gcProjectQtwj);
            
            //查询流程图
            GcProjectFlow gcProjectFlow = new GcProjectFlow();
            gcProjectFlow.setGcProjectid(gcProjectQtwj.getGcProjectid());
            gcProjectFlow = gcProjectFlowService.selectGcProjectFlowList(gcProjectFlow).get(0);
            
            GcProjectFlow obj = new GcProjectFlow();
            //判断是否启用项目审批节点
            if(gcProjectFlow.getSjtz()==1 && gcProjectFlow.getZjbj()==1 && 
            		gcProjectFlow.getCbyg()==1 && gcProjectFlow.getHtxq()==1){
            	obj.setXmps(1);
            }
            obj.setQtwj(1);
            obj.setGcProjectid(gcProjectFlow.getGcProjectid());
            gcProjectFlowService.updateGcProjectFlow(obj);
        }
        catch (Exception e){
            log.error("上传文件！", e);
            return error(e.getMessage());
        }
    	
        return toAjax(1);
    }

    /**
     * 修改其他文件
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        GcProjectQtwj gcProjectQtwj = gcProjectQtwjService.selectGcProjectQtwjById(id);
        GcProject gcProject = gcProjectService.selectGcProjectById(gcProjectQtwj.getGcProjectid());
    	mmap.put("gcProject", gcProject);
    	
    	if(gcProjectQtwj.getZilwj()!=null && !gcProjectQtwj.getZilwj().equals("")){
        	String[] zlis = gcProjectQtwj.getZilwj().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += RuoYiConfig.getOnPath()+zlis[i]+",";
        	}
        	gcProjectQtwj.setZilwj(file);
        }
    	mmap.put("gcProjectQtwj", gcProjectQtwj);
        return prefix + "/edit";
    }
    
    /**
     * 修改其他文件
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap)
    {
        GcProjectQtwj gcProjectQtwj = gcProjectQtwjService.selectGcProjectQtwjById(id);
        GcProject gcProject = gcProjectService.selectGcProjectById(gcProjectQtwj.getGcProjectid());
    	mmap.put("gcProject", gcProject);
    	
    	if(gcProjectQtwj.getZilwj()!=null && !gcProjectQtwj.getZilwj().equals("")){
        	String[] zlis = gcProjectQtwj.getZilwj().split(",");
        	String file = "";
        	for(int i=0;i<zlis.length;i++){
        		file += RuoYiConfig.getOnPath()+zlis[i]+",";
        	}
        	gcProjectQtwj.setZilwj(file);
        }
    	mmap.put("gcProjectQtwj", gcProjectQtwj);
        return prefix + "/detail";
    }

    /**
     * 修改保存其他文件
     */
    @Log(title = "其他文件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GcProjectQtwj gcProjectQtwj)
    {
    	try{
            gcProjectQtwjService.updateGcProjectQtwj(gcProjectQtwj);
        }
        catch (Exception e){
            log.error("上传文件！", e);
            return error(e.getMessage());
        }
    	
        return toAjax(1);
    }

    /**
     * 删除其他文件
     */
    @RequiresPermissions("gcgl:qtwj:remove")
    @Log(title = "其他文件", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(gcProjectQtwjService.deleteGcProjectQtwjByIds(ids));
    }
    
    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception{
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}
